from datetime import datetime
import sys
from PySide6.QtWidgets import (QApplication, QDialog, QTableWidget, QTableWidgetItem, 
                             QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, 
                             QWidget, QMessageBox, QComboBox, QHeaderView)
from PySide6.QtCore import Qt, QDate, QTime, QDateTime, QPoint, QEvent,Signal

from gui.utils.api import API
from gui.window.DateTimeRange import DateTimeRangeEdit


def timestamp_to_string(timestamp, format='%Y-%m-%d %H:%M:%S'):
    """
    把时间戳转换为字符串
    :param timestamp: 时间戳（可以是int、float类型）
    :param format: 输出的字符串格式，默认是 '%Y-%m-%d %H:%M:%S'
    :return: 格式化后的时间字符串
    """
    # 把时间戳转换为datetime对象
    dt_object = datetime.fromtimestamp(timestamp)
    # 按照指定格式把datetime对象格式化为字符串
    return dt_object.strftime(format)


class TableWidget_Base_Datamanager(QDialog):
    """表格管理基类，提供基础的表格展示、分页、搜索功能"""
    
    def __init__(self, api: API=None):
        super().__init__()
        self.api = api
        self.data = []
        self.current_page = 1
        self.items_per_page = 10
        self.total_pages = 0
        self.filtered_data = []
        self.setup_ui()
        
    def setup_ui(self):
        """设置用户界面"""
        # 创建主布局
        main_layout = QVBoxLayout()
        
        # 顶部按钮区域
        self.top_button_layout = QHBoxLayout()
        self.setup_top_buttons()
        
        # 搜索区域
        search_layout = QVBoxLayout()
        self.search_h1_layout = QHBoxLayout()
        
        start_datetime: QDateTime = QDateTime(QDate.currentDate().addDays(-365), QTime(0, 0, 0))
        end_datetime: QDateTime = QDateTime(QDate.currentDate(), QTime(23, 59, 59))
        self.search_create_field = DateTimeRangeEdit(start_datetime=start_datetime, end_datetime=end_datetime)
        self.search_update_field = DateTimeRangeEdit(start_datetime=start_datetime, end_datetime=end_datetime)
        self.search_h2_layout = QHBoxLayout()
        self.search_h2_layout.addWidget(QLabel("创建时间:"))
        self.search_h2_layout.addWidget(self.search_create_field)
        self.search_h2_layout.addWidget(QLabel("更新时间:"))
        self.search_h2_layout.addWidget(self.search_update_field)
        
        
        # 设置搜索字段
        self.setup_search_fields()
        
        # 搜索按钮
        self.search_button = QPushButton("搜索")
        self.search_button.clicked.connect(self.search_data)
        
        # 添加到搜索布局
        self.search_h1_layout.addStretch()
        self.search_h2_layout.addWidget(self.search_button)
        self.search_h2_layout.addStretch()
        search_layout.addLayout(self.search_h1_layout)
        search_layout.addLayout(self.search_h2_layout)
        
        # 表格
        self.table = QTableWidget()
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        
        # 分页控制
        pagination_layout = QHBoxLayout()
        
        # 上一页按钮
        self.prev_button = QPushButton("上一页")
        self.prev_button.clicked.connect(self.prev_page)
        
        # 当前页码显示
        self.page_label = QLabel(f"第 {self.current_page} 页，共 {self.total_pages} 页")
        
        # 下一页按钮
        self.next_button = QPushButton("下一页")
        self.next_button.clicked.connect(self.next_page)
        
        # 每页显示数量
        self.items_per_page_combo = QComboBox()
        self.items_per_page_combo.addItems(["10", "20", "50", "100"])
        self.items_per_page_combo.setCurrentText(str(self.items_per_page))
        self.items_per_page_combo.currentTextChanged.connect(self.change_items_per_page)
        
        # 添加到分页布局
        pagination_layout.addWidget(self.prev_button)
        pagination_layout.addWidget(self.page_label)
        pagination_layout.addWidget(self.next_button)
        pagination_layout.addStretch()
        pagination_layout.addWidget(QLabel("每页显示:"))
        pagination_layout.addWidget(self.items_per_page_combo)
        
        # 添加所有布局到主布局
        main_layout.addLayout(search_layout)
        main_layout.addLayout(self.top_button_layout)
        main_layout.addWidget(self.table)
        main_layout.addLayout(pagination_layout)
        
        # 设置布局
        self.setLayout(main_layout)
        
        # 更新分页按钮状态
        self.update_pagination_buttons()
    
    def setup_top_buttons(self):
        """设置顶部按钮，子类可重写此方法添加自定义按钮"""
        pass
    
    def setup_search_fields(self):
        """设置搜索字段，子类可重写此方法添加自定义搜索字段"""
        pass
    
    def set_table_columns(self, headers):
        """设置表格列头"""
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
    
    def update_table(self, data):
        """更新表格显示"""
        current_page_data = data.get("result", [])
        # 清空表格
        self.table.setRowCount(0)
        
        # 填充表格
        for row, item in enumerate(current_page_data):
            self.table.insertRow(row)
            self.fill_table_row(row, item)
        
        # 更新分页信息
        self.total_pages = data.get("page_total", 0)
        self.current_page = data.get("page", 1)
        self.page_label.setText(f"第 {self.current_page} 页，共 {self.total_pages} 页")
        
        # 更新分页按钮状态
        self.update_pagination_buttons()
    
    def fill_table_row(self, row, item):
        """填充表格行数据，子类需实现此方法"""
        raise NotImplementedError("子类必须实现fill_table_row方法")
    
    def update_pagination_buttons(self):
        """更新分页按钮状态"""
        self.prev_button.setEnabled(self.current_page > 1)
        self.next_button.setEnabled(self.current_page < self.total_pages)
    
    def prev_page(self):
        """上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.load_data()
    
    def next_page(self):
        """下一页"""
        if self.current_page < self.total_pages:
            self.current_page += 1
            self.load_data()
    
    def change_items_per_page(self, text):
        """更改每页显示数量"""
        self.items_per_page = int(text)
        self.current_page = 1  # 重置到第一页
        self.load_data()
    
    def get_query_params(self):
        """获取查询参数，子类可重写此方法添加自定义查询参数"""
        return {
            "page": self.current_page,
            "limit": self.items_per_page,
        }
    
    def load_data(self):
        """加载数据，子类需实现此方法"""
        raise NotImplementedError("子类必须实现load_data方法")
    
    def search_data(self):
        """搜索数据"""
        self.current_page = 1
        self.load_data()
    
    def show(self):
        """搜索数据"""
        self.load_data()
        super().show()
        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TableWidget_Datamanager()
    window.show()
    sys.exit(app.exec())